﻿package cn.poco.pepsi.util;

import java.io.File;
import java.io.FileInputStream;
import java.lang.ref.SoftReference;
import java.util.HashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;

public class AsyncLoadImageService {
	private Context context;
	private ExecutorService threadPool;
	public HashMap<String, SoftReference<Bitmap>> imageCache;
	private boolean roundedCorner;
	private int requestWidth;

	public AsyncLoadImageService(Context context) {
		this.context = context;
		imageCache = new HashMap<String, SoftReference<Bitmap>>();
		threadPool = Executors.newCachedThreadPool();
	}

	public Bitmap loadBitmap(final String imageUrl, final cn.poco.pepsi.util.AsyncImageLoader.ImageCallback imageCallback, boolean roundedCorner,
			boolean compress, int screenWidth) {
		this.roundedCorner = roundedCorner;
		this.requestWidth = screenWidth;
		if (imageCache.containsKey(imageUrl)) {
			SoftReference<Bitmap> softReference = imageCache.get(imageUrl);
			Bitmap bitmap = softReference.get();
			if (bitmap != null && !bitmap.isRecycled()) {
				return bitmap;
			}
		}
		final Handler handler = new Handler() {
			public void handleMessage(Message message) {
				imageCallback.imageLoaded((Bitmap) message.obj, imageUrl);
			}
		};
		threadPool.execute(new DecodeBitmapThread(imageUrl, handler));
		return null;
	}

	private final class DecodeBitmapThread implements Runnable {
		private String imageUrl;
		private Handler handler;

		public DecodeBitmapThread(String imageUrl, Handler handler) {
			this.imageUrl = imageUrl;
			this.handler = handler;
		}

		public void run() {
			try {
				String uri = new DownloadImage(context).download(imageUrl);
				Bitmap bitmap = null;
				if (requestWidth != 0) {// 按宽要求压缩图片
					BitMapDecodeService bitMapDecodeService = new BitMapDecodeService();
					File reqFile = new File(uri);
					if (reqFile.exists()) {
						bitmap = ImageCompress.getCompressBmp(bitMapDecodeService.decodeStream(new FileInputStream(
								reqFile), new FileInputStream(reqFile), requestWidth), requestWidth);
					}
				} else {
					bitmap = BitmapFactory.decodeFile(uri);
				}
				if (bitmap != null) {
					if (roundedCorner) {// 圆角压缩图片
						bitmap = RoundedCornerImage.getRoundedCornerBitmap(bitmap);
					}
					imageCache.put(imageUrl, new SoftReference<Bitmap>(bitmap));
					Message message = handler.obtainMessage(0, bitmap);
					handler.sendMessage(message);
				} else {
					File file = new File(uri);
					if (file.exists()) {
						file.delete();
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}

		}
	}

	public interface ImageCallback {
		public void imageLoaded(Bitmap imageBitmap, String imageUrl);
	}

}
